﻿#region Using directives
using System;
using System.Collections.Generic;
using System.ServiceModel.Syndication;
using System.Web.UI;
using System.Xml;
using ProcolDemo.I18N;
using ProcolDemo.IdeasReference;
using ProcolDemo.ProjectsReference;
using ProcolDemo.Updates;
using ProcolDemo.User;

#endregion

namespace ProcolDemo {
    public partial class RssGenerator : Page {
        private readonly IdeasService ideaService = new IdeasService();
        private readonly ProjectService projectService = new ProjectService();

        protected void Page_Load(object sender, EventArgs e) {
            var updateService = new UpdateService();

            Response.Buffer = false;
            Response.Clear();
            Response.ContentType = "application/rss+xml";

            using (XmlWriter writer = XmlWriter.Create(Response.OutputStream)) {
                var userService = new UserService();
                var I18N = new I18NService();
                int uidRequest = Common.GetUserId(Request);
                String user = userService.GetUserUsername(uidRequest);

                if (Request["type"] != null) {
                    String rssType = Request["type"].ToLower();
                    String rssTypeTitle = String.Format("{0}{1}", rssType[0].ToString().ToUpper(), rssType.Substring(1));
                    var wantedCats = new List<String>();
                    bool isGlobal = false;

                    int objectId;
                    if (!Int32.TryParse(Request["id"], out objectId))
                        objectId = -1;

                    if (rssType.Equals("global")) {
                        wantedCats.Add("system");
                        wantedCats.Add("ideas");
                        wantedCats.Add("projects");
                        wantedCats.Add("members");

                        isGlobal = true;
                    } else
                        wantedCats.Add(rssType);

                    var feed = new SyndicationFeed(String.Format("{0}: {1}", user, rssTypeTitle), "ProCol",
                                                   new Uri("http://localhost:1059/"));
                    feed.Authors.Add(new SyndicationPerson("admin@procol.com.mx", "ProCol", "http://localhost:1059"));
                    feed.Copyright = new TextSyndicationContent("© Copyright 2008 ProCol");
                    feed.Generator = "ProCol RSS 2.0 Generator";

                    var items = new List<SyndicationItem>();
                    int updateNo = 0;

                    foreach (var category in wantedCats) {
                        if (!isGlobal)
                            updateNo = 0;

                        feed.Categories.Add(new SyndicationCategory(category));

                        UpdateHolder[] updates = category.Equals("system")
                                                         ? updateService.GetSystemUpdates()
                                                         : (category.Equals(("ideas"))
                                                                    ? updateService.GetIdeaUpdates(uidRequest, objectId)
                                                                    : (category.Equals(("projects"))
                                                                               ? updateService.GetProjectUpdates(
                                                                                         uidRequest, objectId)
                                                                               : updateService.GetMembersUpdates(
                                                                                         uidRequest)));


                        foreach (var update in updates) {
                            var item = new SyndicationItem {
                                    Id = update.Timestamp.ToShortDateString(),
                                    Title =
                                            SyndicationContent.CreateHtmlContent(
                                                    String.Format(
                                                            I18N.GetTextAccordingToUserId(uidRequest, "UPDATE_NO"),
                                                            ++updateNo)),
                                    Content =
                                            SyndicationContent.CreateHtmlContent(
                                                    String.Format(
                                                            I18N.GetTextAccordingToUserId(uidRequest, update.EntryId),
                                                            update.EntryId, update.ObjectId, update.Origin,
                                                            update.Target, update.Timestamp,
                                                            userService.GetUserUsername(update.Origin),
                                                            userService.GetUserUsername(update.Target),
                                                            GetObjectText(category, update.ObjectId, update.EntryId))),
                                    Summary =
                                            SyndicationContent.CreateHtmlContent(
                                                    String.Format(
                                                            I18N.GetTextAccordingToUserId(uidRequest, update.EntryId),
                                                            update.EntryId, update.ObjectId, update.Origin,
                                                            update.Target, update.Timestamp,
                                                            userService.GetUserUsername(update.Origin),
                                                            userService.GetUserUsername(update.Target),
                                                            GetObjectText(category, update.ObjectId, update.EntryId))),
                                    PublishDate = update.Timestamp
                            };

                            var itemLink = new SyndicationLink
                            {Title = "ProCol", Uri = new Uri("http://localhost:1059/")};

                            item.Links.Add(itemLink);
                            item.Categories.Add(new SyndicationCategory(category));

                            items.Add(item);
                        }
                    }

                    feed.Items = items;

                    var rssFormatter = new Rss20FeedFormatter(feed);

                    if (writer != null) {
                        rssFormatter.WriteTo(writer);
                        writer.Flush();
                    }
                }
                Response.End();
            }
        }

        private string GetObjectText(IEquatable<string> category, int id, String entry) {
            return category.Equals("ideas") || entry.Contains("_IDEA_")
                           ? ideaService.GetIdeaName(id)
                           : (category.Equals("projects") || entry.Contains("_PROJECT_")
                                      ? projectService.GetProject(id).name
                                      : "NULL-" + category);
        }
    }
}